//
//  SceneDelegate.swift
//  Reader
//
//  Created by home on 2019/10/10.
//  Copyright © 2019 codeguesser. All rights reserved.
//

import UIKit
import AVFoundation
import MediaPlayer
import PDFKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }
        window?.backgroundColor = .systemBackground
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
        if UIPasteboard.general.hasStrings {
            let t = UIPasteboard.general.strings?.filter({$0.isNotEmptyOrBlank}).first ?? ""
            guard t.isNotEmptyOrBlank else { return  }
            
            if let nav = (self.window?.rootViewController as? UINavigationController){
                func realDismiss(){
                    let vc = PreviewViewController(nibName: PreviewViewController.identifier)
                    vc.title = "粘贴板:\(Int(Date().timeIntervalSince1970))"
                    vc.datas = t.split(2500)
                    nav.pushViewController(vc, animated: true)
                }
                if let vc = nav.presentedViewController {
                    vc.dismiss(animated: true) {
                        realDismiss()
                    }
                }
                realDismiss()
            }
            UIPasteboard.general.strings = []
        }
    }
    
    var _bgTaskId:UIBackgroundTaskIdentifier?
    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
        guard (UIApplication.shared.delegate as? AppDelegate)?.isRuningSpeaking != nil else {
            return
        }
        let session = AVAudioSession.sharedInstance()

        do {
            try? session.setActive(true)
            try? session.setCategory(AVAudioSession.Category.playback)
        }
        _bgTaskId = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
        if _bgTaskId != UIBackgroundTaskIdentifier.invalid{
            UIApplication.shared.endBackgroundTask(_bgTaskId!)
        }
    }
    
    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }

    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        func uploadFile(url:URL)->URL? {
            var copyedURL:URL?
            if let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).first{
                let newPath = dir + "/" + url.lastPathComponent
                do {
                    
                    func newName(oldPath:String,index:Int)->String{
                        var p = oldPath
                        if index > 0 {
                            let u = URL(fileURLWithPath: oldPath)
                            p = u.path.replacingOccurrences(of: "."+u.pathExtension, with: "_\(index)."+u.pathExtension)
                        }
                        if FileManager.default.isReadableFile(atPath: p) {
                            return newName(oldPath: oldPath, index: index + 1)
                        }else{
                            return p
                        }
                    }
                    try FileManager.default.copyItem(atPath: url.path, toPath: newName(oldPath: newPath, index: 0))
                    copyedURL = URL(fileURLWithPath: newPath, isDirectory: false)
                    return copyedURL
                } catch  {
                    UIAlertController.alertMessage(error.localizedDescription)
                    return nil
                }
            }
            return nil
        }
        let urls = URLContexts.compactMap({uploadFile(url: $0.url)})
        let vc = MYPreviewController()
        vc.files = urls
        vc.importAction = {[weak self] i in
            let url = urls[i]
            if let pdf = PDFDocument(url: url) {
                
                let vc = PreviewViewController(nibName: PreviewViewController.identifier)
                vc.title = url.lastPathComponent
                vc.datas = (0..<pdf.pageCount).compactMap({pdf.page(at: $0)?.string})
                (self?.window?.rootViewController as? UINavigationController)?.pushViewController(vc, animated: true)
            }
        }
        if let nav = window?.rootViewController as? UINavigationController{
            func realDismiss(){
                let previewNavigationController = PreviewNavigationController(navigationBarClass:nil, toolbarClass: PreviewControllerToolbar.self)
                previewNavigationController.modalPresentationStyle = .overFullScreen
                previewNavigationController.pushViewController(vc, animated: false)
                nav.present(previewNavigationController, animated:true, completion: {
                    vc.currentPreviewItemIndex = 0
                })
            }
            if let vc = nav.presentedViewController {
                vc.dismiss(animated: true) {
                    realDismiss()
                }
            }
            realDismiss()
        }
    }
}

